﻿using SlimDX;
using SlimDX.DirectInput;


namespace InsTron
{
    class GameInputHandler
    {
        private GameView gameView;
        private Keyboard keyboard;
        private KeyboardState keys;

        private bool[] pressedLeft;
        private bool[] pressedRight;
        private bool pressedPause;


        public GameInputHandler(GameView gameView, Keyboard keyboard)
        {
            this.gameView = gameView;
            this.keyboard = keyboard;

            ResetInputState();
            GameControls.Initialize();
        }


        private void ResetInputState()
        {
            pressedLeft = new bool[2];
            pressedRight = new bool[2];
            for (int i = 0; i < 2; ++i)
            {
                pressedLeft[i] = false;
                pressedRight[i] = false;
            }
            pressedPause = false;
        }


        public void ReadKeyboard()
        {
            keys = keyboard.GetCurrentState();
            
            ReadPause();
            ReadPlayerControls(0);
            ReadPlayerControls(1);
        }


        private void ReadPause()
        {
            if (keys.IsPressed(GameControls.pauseKey) && !pressedPause)
            {
                gameView.PauseGame();
            }
            pressedPause = keys.IsPressed(GameControls.pauseKey);
        }


        private void ReadPlayerControls(int idx)
        {
            gameView.EnableBoost(idx, keys.IsPressed(GameControls.accelerateKey[idx]));
            gameView.EnableBrake(idx, keys.IsPressed(GameControls.brakeKey[idx]));
            ReadTurns(idx);
        }


        private void ReadTurns(int idx)
        {
            if (keys.IsPressed(GameControls.leftKey[idx]) && !pressedLeft[idx])
            {
                gameView.ProcessTurn(idx, true);
            }
            pressedLeft[idx] = keys.IsPressed(GameControls.leftKey[idx]);

            if (keys.IsPressed(GameControls.rightKey[idx]) && !pressedRight[idx])
            {
                gameView.ProcessTurn(idx, false);
            }
            pressedRight[idx] = keys.IsPressed(GameControls.rightKey[idx]);
        }
    }
}
